<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>阻塞队列——LinkedBlockingQueue源码分析 | 博客主页 | 世界是个球，前方总有路！</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="Java容器">
    <meta name="description" content="一、前言&amp;emsp;&amp;emsp;这几天准备研究一下Java中阻塞队列的实现。Java中的阻塞队列有七种，我准备逐一研究它们的源码，然后每一个阻塞队列写一篇分析博客，这是其中的第二篇。这篇博客就来说一说阻塞队列中比较常用的一种——LinkedBlockingQueue。 &amp;emsp;&amp;emsp;之前写了一篇分析ArrayBlockingQueue源码的博客，感兴趣的可以看一看：阻塞队列——Array">
<meta property="og:type" content="article">
<meta property="og:title" content="阻塞队列——LinkedBlockingQueue源码分析">
<meta property="og:url" content="http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="博客主页">
<meta property="og:description" content="一、前言&amp;emsp;&amp;emsp;这几天准备研究一下Java中阻塞队列的实现。Java中的阻塞队列有七种，我准备逐一研究它们的源码，然后每一个阻塞队列写一篇分析博客，这是其中的第二篇。这篇博客就来说一说阻塞队列中比较常用的一种——LinkedBlockingQueue。 &amp;emsp;&amp;emsp;之前写了一篇分析ArrayBlockingQueue源码的博客，感兴趣的可以看一看：阻塞队列——Array">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-11T16:57:45.000Z">
<meta property="article:modified_time" content="2020-04-11T19:36:26.413Z">
<meta property="article:author" content="特务依昂">
<meta property="article:tag" content="Java容器">
<meta name="twitter:card" content="summary">
    
        <link rel="alternate" type="application/atom+xml" title="博客主页" href="/blog/atom.xml">
    
    <link rel="shortcut icon" href="/blog/img/title.png">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/brand.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">特务依昂</h5>
          <a href="mailto:1131564805@qq.com" title="1131564805@qq.com" class="mail">1131564805@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                博客
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/tewuyiang" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/5516635708/" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.cnblogs.com/tuyang1129/" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                博客园
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">阻塞队列——LinkedBlockingQueue源码分析</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">阻塞队列——LinkedBlockingQueue源码分析</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-04-11T16:57:45.000Z" itemprop="datePublished" class="page-time">
  2020-04-12
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/Java%E5%AE%B9%E5%99%A8/">Java容器</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#一、前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">一、前言</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#二、正文"><span class="post-toc-number">2.</span> <span class="post-toc-text">二、正文</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-1-什么是阻塞队列"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">2.1 什么是阻塞队列</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-2-LinkedBlockingQueue类的成员变量"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">2.2 LinkedBlockingQueue类的成员变量</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-3-LinkedBlockingQueue的构造方法"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">2.3 LinkedBlockingQueue的构造方法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-4-入队方法的实现"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">2.4 入队方法的实现</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-5-出队方法的实现"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">2.5 出队方法的实现</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-6-LinkedBlockingQueue的优势与劣势"><span class="post-toc-number">2.6.</span> <span class="post-toc-text">2.6 LinkedBlockingQueue的优势与劣势</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-7-LinkedBlockingQueue的误区"><span class="post-toc-number">2.7.</span> <span class="post-toc-text">2.7 LinkedBlockingQueue的误区</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#三、总结"><span class="post-toc-number">3.</span> <span class="post-toc-text">三、总结</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#四、参考"><span class="post-toc-number">4.</span> <span class="post-toc-text">四、参考</span></a></li></ol>
        </nav>
    </aside>


<article id="post-阻塞队列——LinkedBlockingQueue源码分析"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">阻塞队列——LinkedBlockingQueue源码分析</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-04-12 00:57:45" datetime="2020-04-11T16:57:45.000Z"  itemprop="datePublished">2020-04-12</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/Java%E5%AE%B9%E5%99%A8/">Java容器</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h1><p>&emsp;&emsp;这几天准备研究一下<code>Java</code>中阻塞队列的实现。<code>Java</code>中的阻塞队列有七种，我准备逐一研究它们的源码，然后每一个阻塞队列写一篇分析博客，这是其中的第二篇。这篇博客就来说一说阻塞队列中比较常用的一种——<code>LinkedBlockingQueue</code>。</p>
<p>&emsp;&emsp;之前写了一篇分析<code>ArrayBlockingQueue</code>源码的博客，感兴趣的可以看一看：<a href="https://www.cnblogs.com/tuyang1129/p/12683373.html" target="_blank" rel="noopener">阻塞队列——ArrayBlockingQueue源码分析</a>。</p>
<br>

<h1 id="二、正文"><a href="#二、正文" class="headerlink" title="二、正文"></a>二、正文</h1><h2 id="2-1-什么是阻塞队列"><a href="#2-1-什么是阻塞队列" class="headerlink" title="2.1 什么是阻塞队列"></a>2.1 什么是阻塞队列</h2><p>&emsp;&emsp;在正式分析前，先简单介绍一下什么是阻塞队列。在说阻塞队列前，先要了解<strong>生产者消费者模式</strong>：</p>
<blockquote>
<p><strong>生产者消费者模式</strong>：生产者生产产品，将生产好的产品放入一个缓冲区域，消费者消费产品，它从缓冲区域获取生产者生产的产品进行消费。缓冲区域有容量限制，若缓存区域已经满了，则生产者需要停止生产，等待缓冲区有空闲位置后，再恢复生产；若缓冲区为空，则消费者需要等待，直到缓冲区中有产品后，才能进行消费；</p>
</blockquote>
<p>&emsp;&emsp;阻塞队列就是基于这种模式实现的<strong>队列型容器</strong>。阻塞队列的一般实现是：我们创建队列时，指定队列的容量，当队列中元素的个数已经满时，向队列中添加元素的线程将被阻塞，直到队列不满才恢复运行，将元素添加进去；当队列为空时，向队列获取元素的线程将被阻塞，直到队列不空才恢复运行，从队列中拿出元素。</p>
<p>&emsp;&emsp;以上是阻塞队列的一般实现，根据具体情况的不同，也会有所差异，比如有的是基于链表实现，有的是基于数组实现；有的是阻塞队列的没有容量限制（无界），而有的是有限制的（有界）。我们现在要分析的<strong>LinkedBlockingQueue就是一个基于链表实现的有界阻塞队列</strong>。下面我们就来从源码的角度分析一下<code>LinkedBlockingQueue</code>。</p>
<br>

<h2 id="2-2-LinkedBlockingQueue类的成员变量"><a href="#2-2-LinkedBlockingQueue类的成员变量" class="headerlink" title="2.2 LinkedBlockingQueue类的成员变量"></a>2.2 LinkedBlockingQueue类的成员变量</h2><p>&emsp;&emsp;我们先来看看<code>LinkedBlockingQueue</code>类的成员变量，了解它的成员变量对于我们理解它的实现原理会用很大的帮助：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 记录阻塞队列允许的最大容量 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> capacity;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 使用int的原子类记录队列中元素的个数 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger count = <span class="keyword">new</span> AtomicInteger();</span><br><span class="line"></span><br><span class="line"><span class="comment">/** LinkedBlockingQueue基于链表实现，head记录链表头节点 */</span></span><br><span class="line"><span class="keyword">transient</span> Node&lt;E&gt; head;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** LinkedBlockingQueue基于链表实现，last记录链尾头节点 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">transient</span> Node&lt;E&gt; last;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** ReentrantLock锁对象，用来保证获取元素时的线程同步 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ReentrantLock takeLock = <span class="keyword">new</span> ReentrantLock();</span><br><span class="line"></span><br><span class="line"><span class="comment">/** takeLock上创建的条件对象，在队列为空时，通过此对象来阻塞消费者线程 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Condition notEmpty = takeLock.newCondition();</span><br><span class="line"></span><br><span class="line"><span class="comment">/** ReentrantLock锁对象，用来保证添加元素时的线程同步 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ReentrantLock putLock = <span class="keyword">new</span> ReentrantLock();</span><br><span class="line"></span><br><span class="line"><span class="comment">/** putLock上创建的条件对象，在队列满时，通过此对象来阻塞生产者线程 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Condition notFull = putLock.newCondition();</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;通过以上成员变量，我们可以知道很多信息：<strong>LinkedBlockingQueue是基于链表实现的，且有capacity变量证明它是一个有界阻塞队列；成员变量中有两个lock对象，分别用来同步生产者线程和消费者线程，减小了锁的粒度，生产者和消费者可以同时运行，这两个锁对象使用默认构造函数创建，也就是说创建的是非公平锁</strong>。既然<code>LinkedBlockingQueue</code>是由链表实现，那我们就来看看链表的节点实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 节点值</span></span><br><span class="line">    E item;</span><br><span class="line">    <span class="comment">// 下一个节点的引用</span></span><br><span class="line">    Node&lt;E&gt; next;</span><br><span class="line"></span><br><span class="line">    Node(E x) &#123; item = x; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;可以看到，<code>Node</code>类的实现非常简单，一个存储值的变量，一个指向下一个节点的引用，仅此而已。接下来我们看看构造方法：</p>
<h2 id="2-3-LinkedBlockingQueue的构造方法"><a href="#2-3-LinkedBlockingQueue的构造方法" class="headerlink" title="2.3 LinkedBlockingQueue的构造方法"></a>2.3 LinkedBlockingQueue的构造方法</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 带参构造方法，参数为阻塞队列的容量 */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">LinkedBlockingQueue</span><span class="params">(<span class="keyword">int</span> capacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 容量必须大于0</span></span><br><span class="line">    <span class="keyword">if</span> (capacity &lt;= <span class="number">0</span>) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException();</span><br><span class="line">    <span class="comment">// 记录容量</span></span><br><span class="line">    <span class="keyword">this</span>.capacity = capacity;</span><br><span class="line">    <span class="comment">// 初始化链表，创建一个无值的Node，头尾指针均指向它</span></span><br><span class="line">    last = head = <span class="keyword">new</span> Node&lt;E&gt;(<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 默认构造方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">LinkedBlockingQueue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 调用带参构造方法，默认容量为int的最大值</span></span><br><span class="line">    <span class="keyword">this</span>(Integer.MAX_VALUE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;构造方法的逻辑也比较简单，唯一值得注意的是：<strong>若使用默认构造方法创建，则阻塞队列的默认容量为int的最大值</strong>。</p>
<br>

<h2 id="2-4-入队方法的实现"><a href="#2-4-入队方法的实现" class="headerlink" title="2.4 入队方法的实现"></a>2.4 入队方法的实现</h2><p>&emsp;&emsp;对于一个阻塞队列来说，最核心的就是它入队和出队的实现，下面我们就来分析一下<code>LinkedBlockingQueue</code>类中入队方法的实现。元素入队的方法有多个，我们先来分析其中最核心的方法——<code>put</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">put</span><span class="params">(E e)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    <span class="comment">// 新元素不能为空</span></span><br><span class="line">    <span class="keyword">if</span> (e == <span class="keyword">null</span>) </span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 初始化一个c变量，后面用于记录插入新元素前，队列中元素的个数</span></span><br><span class="line">    <span class="keyword">int</span> c = -<span class="number">1</span>;</span><br><span class="line">    <span class="comment">// 将新元素封装成一个Node</span></span><br><span class="line">    Node&lt;E&gt; node = <span class="keyword">new</span> Node&lt;E&gt;(e);</span><br><span class="line">    <span class="comment">// 因为是添加元素，所以这里使用put锁进行线程同步，先获取put锁</span></span><br><span class="line">    <span class="keyword">final</span> ReentrantLock putLock = <span class="keyword">this</span>.putLock;</span><br><span class="line">    <span class="comment">// 获取记录元素个数的变量</span></span><br><span class="line">    <span class="keyword">final</span> AtomicInteger count = <span class="keyword">this</span>.count;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 在正式操作前，先使用putLock加锁，调用的是lockInterruptibly方法</span></span><br><span class="line">    <span class="comment">// 这个方法在在线程被阻塞时可以响应中断，使用它是防止线程一直无法添加成功，</span></span><br><span class="line">    <span class="comment">// 长期被阻塞在此处</span></span><br><span class="line">    putLock.lockInterruptibly();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 添加元素前线判断队列中元素是否已经满了，</span></span><br><span class="line">        <span class="comment">// 若满了则使用notFull对象，让当前线程阻塞，直到被另一个线程唤醒</span></span><br><span class="line">        <span class="comment">// 使用while而不是if，目的是防止线程被唤醒时，</span></span><br><span class="line">        <span class="comment">// 队列仍然是满的，所以需要重复判断</span></span><br><span class="line">        <span class="keyword">while</span> (count.get() == capacity) &#123;</span><br><span class="line">            notFull.await();</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 调用enqueue方法将新节点加入队列的尾部</span></span><br><span class="line">        enqueue(node);</span><br><span class="line">        <span class="comment">// getAndIncrement方法返回count的旧值，然后让count+1</span></span><br><span class="line">        c = count.getAndIncrement();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/**************关键点1****************/</span></span><br><span class="line">        <span class="comment">// c + 1就是插入当前这个节点后，队列中元素的数量</span></span><br><span class="line">        <span class="comment">// 若插入这个元素后，队列依旧没有满，则唤醒一个生产者线程</span></span><br><span class="line">        <span class="comment">// 也就是向队列中添加元素的线程（前提是有这么一个线程）。</span></span><br><span class="line">        <span class="comment">// 为什么是在添加一个元素后，唤醒另外一个生产者线程，</span></span><br><span class="line">        <span class="comment">// 而不是在有线程获取元素后，唤醒一个生产者线程呢，这不是才正常吗？</span></span><br><span class="line">        <span class="comment">// 答案就是消费者线程使用的是take锁，而唤醒生产者线程需要的是put锁，</span></span><br><span class="line">        <span class="comment">// 为了减少额外加锁解锁的次数，我们就可以在这里唤醒生产者线程，</span></span><br><span class="line">        <span class="comment">// 因为这里在添加元素前，已经获取了put锁了，不需要重复获取。</span></span><br><span class="line">        <span class="keyword">if</span> (c + <span class="number">1</span> &lt; capacity)</span><br><span class="line">            notFull.signal();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 解锁</span></span><br><span class="line">        putLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**************关键点2****************/</span></span><br><span class="line">    <span class="comment">// c表示插入之前，队列中元素的个数，若插入之前c == 0，</span></span><br><span class="line">    <span class="comment">// 表示在插入前，队列是空，意味着很有可能存在正在等待的消费者线程</span></span><br><span class="line">    <span class="comment">// 于是调用signalNotEmpty方法唤醒一个消费者线程。</span></span><br><span class="line">    <span class="comment">// 可以看到，只有当添加元素之前，队列为空，这里才会唤醒一个消费者线程。</span></span><br><span class="line">    <span class="comment">// 但是可能有多个消费者线程在等待，此时唤醒一个，那剩下的那些怎么办？</span></span><br><span class="line">    <span class="comment">// 答案就是可以在获取元素的方法中唤醒它们，原理就是上面那段很长的注释</span></span><br><span class="line">    <span class="keyword">if</span> (c == <span class="number">0</span>)</span><br><span class="line">        signalNotEmpty();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 此方法将节点加入到链表的末尾 */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">enqueue</span><span class="params">(Node&lt;E&gt; node)</span> </span>&#123;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * 以下代码可以分解为：</span></span><br><span class="line"><span class="comment">     * last.next = node;</span></span><br><span class="line"><span class="comment">     * last = node</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    last = last.next = node;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 此方法用于唤醒一个消费者线程 */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">signalNotEmpty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 因为消费者线程是获取元素，所以使用的是take锁</span></span><br><span class="line">    <span class="keyword">final</span> ReentrantLock takeLock = <span class="keyword">this</span>.takeLock;</span><br><span class="line">    takeLock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// notEmpty由take锁创建，所以需要先锁定take锁，再调用signal方法</span></span><br><span class="line">        <span class="comment">// 否则将抛出异常</span></span><br><span class="line">        notEmpty.signal();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        takeLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;以上就是<code>put</code>方法的实现，逻辑还是比较简单的，它的过程概括来说就是：<strong>将需要添加的元素封装成为一个Node，然后获取put锁，在添加前先判断当前队列是否已经满了，若满了，则会被阻塞等待，直到被其他线程唤醒；队列未满时，将元素添加到链表的末尾，若添加完后，队列依旧没有满，则再唤醒一个生产者线程。添加元素完成后，若判断添加前，队列为空，则很有可能有消费者线程在等待，于是唤醒一个消费者线程</strong>。<code>put</code>方法中，我用注释标记出了两个关键点，这两个关键点是作者对锁的一个优化，<code>take</code>方法中也有这两个关键点，它们相互对应，请结合<code>take</code>方法理解。下面我们再来看看另一个添加元素的方法<code>offer</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 向队列中添加元素，但是不会阻塞 */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">offer</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判空</span></span><br><span class="line">    <span class="keyword">if</span> (e == <span class="keyword">null</span>) </span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    <span class="comment">// 获取记录元素数量的count变量</span></span><br><span class="line">    <span class="keyword">final</span> AtomicInteger count = <span class="keyword">this</span>.count;</span><br><span class="line">    <span class="comment">// 如果当前队列已经满了，则直接返回false，不进行添加</span></span><br><span class="line">    <span class="keyword">if</span> (count.get() == capacity)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 此变量的作用于put方法中一致</span></span><br><span class="line">    <span class="keyword">int</span> c = -<span class="number">1</span>;</span><br><span class="line">    <span class="comment">// 封装成Node</span></span><br><span class="line">    Node&lt;E&gt; node = <span class="keyword">new</span> Node&lt;E&gt;(e);</span><br><span class="line">    <span class="keyword">final</span> ReentrantLock putLock = <span class="keyword">this</span>.putLock;</span><br><span class="line">    <span class="comment">// 因为是添加元素，所以使用put锁进行锁定，这里调用的lock()方法</span></span><br><span class="line">    <span class="comment">// lock方法不响应中断，这里不需要响应中断，所以选择使用lock，</span></span><br><span class="line">    <span class="comment">// 不需要响应中断是因为这个方法并不会阻塞线程</span></span><br><span class="line">    putLock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 再次判断当前队列是否满了，为什么再次判断？</span></span><br><span class="line">        <span class="comment">// 因为在上一次判断后，CPU可能暂停了当前线程，转而执行其他线程</span></span><br><span class="line">        <span class="comment">// 在这个过程中可能有其他线程向队列中添加了元素</span></span><br><span class="line">        <span class="keyword">if</span> (count.get() &lt; capacity) &#123;</span><br><span class="line">            <span class="comment">// 调用enqueue方法将元素添加到队列的尾部</span></span><br><span class="line">            enqueue(node);</span><br><span class="line">            <span class="comment">// 此处操作与put方法中相同，不重复描述</span></span><br><span class="line">            c = count.getAndIncrement();</span><br><span class="line">            <span class="keyword">if</span> (c + <span class="number">1</span> &lt; capacity)</span><br><span class="line">                notFull.signal();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 解锁</span></span><br><span class="line">        putLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 此处操作与put方法相同</span></span><br><span class="line">    <span class="keyword">if</span> (c == <span class="number">0</span>)</span><br><span class="line">        signalNotEmpty();</span><br><span class="line">    <span class="comment">// c记录的是添加前，队列中元素的个数，不可能出现负数，所以此处返回的一定是true</span></span><br><span class="line">    <span class="keyword">return</span> c &gt;= <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此方法向队列中添加元素，若队列已经满了，则线程被阻塞，但是参数中限制了阻塞时间</span></span><br><span class="line"><span class="comment"> * 若超时后，当前线程还没有添加成功，则不继续等待，直接返回</span></span><br><span class="line"><span class="comment"> * 参数：</span></span><br><span class="line"><span class="comment"> * 	1、timeout：超时时间的数量级，一个long类型的整数</span></span><br><span class="line"><span class="comment"> *	2、unit：timeout的单位，例如TimeUnit.SECOND表示的就是秒</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">offer</span><span class="params">(E e, <span class="keyword">long</span> timeout, TimeUnit unit)</span></span></span><br><span class="line"><span class="function">    <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (e == <span class="keyword">null</span>) </span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    <span class="comment">// 将超时时间转换为纳秒</span></span><br><span class="line">    <span class="keyword">long</span> nanos = unit.toNanos(timeout);</span><br><span class="line">    <span class="comment">// 以下几句与put方法相同</span></span><br><span class="line">    <span class="keyword">int</span> c = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">final</span> ReentrantLock putLock = <span class="keyword">this</span>.putLock;</span><br><span class="line">    <span class="keyword">final</span> AtomicInteger count = <span class="keyword">this</span>.count;</span><br><span class="line">    putLock.lockInterruptibly();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 若当前队列已经满了，则线程需要进入等待</span></span><br><span class="line">        <span class="keyword">while</span> (count.get() == capacity) &#123;</span><br><span class="line">            <span class="comment">// 判断等待的剩余时间是否&lt;=0，若满足此条件，表示等待时间已经超时</span></span><br><span class="line">            <span class="keyword">if</span> (nanos &lt;= <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            <span class="comment">// 使用notFull对象让当前线程阻塞，传入需要阻塞的时间，但是这个方法并不精确</span></span><br><span class="line">            <span class="comment">// 所以会返回剩余需要阻塞的时间，这也就是为什么上一句需要判断nanos &lt;= 0</span></span><br><span class="line">            nanos = notFull.awaitNanos(nanos);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 以下操作和put相同</span></span><br><span class="line">        enqueue(<span class="keyword">new</span> Node&lt;E&gt;(e));</span><br><span class="line">        c = count.getAndIncrement();</span><br><span class="line">        <span class="keyword">if</span> (c + <span class="number">1</span> &lt; capacity)</span><br><span class="line">            notFull.signal();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        putLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (c == <span class="number">0</span>)</span><br><span class="line">        signalNotEmpty();</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;以上就是<code>offer</code>方法的实现，可以看到，<code>offer</code>方法被重载了两次，第一个是直接向队列中添加元素，不会被阻塞，添加成功返回<code>true</code>，失败则返回<code>false</code>；而另外一个<code>offer</code>方法，在无法添加时会被阻塞，但是限定了阻塞的超时时间，若超时还未添加成功，则不会继续等待。</p>
<br>

<h2 id="2-5-出队方法的实现"><a href="#2-5-出队方法的实现" class="headerlink" title="2.5 出队方法的实现"></a>2.5 出队方法的实现</h2><p>&emsp;&emsp;看完了入队的方法实现，下面再来看看出队的方法实现。出队的方法主要有两个，<code>poll</code>方法，以及阻塞队列的核心方法之一——<code>take</code>方法。下面我们就先来看看<code>take</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">take</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    E x;</span><br><span class="line">    <span class="comment">// 此变量的作用与put方法中一致，用来记录插入前，队列中元素的个数</span></span><br><span class="line">    <span class="keyword">int</span> c = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">final</span> AtomicInteger count = <span class="keyword">this</span>.count;</span><br><span class="line">    <span class="comment">// 由于是向队列中获取元素，所以使用的是take锁</span></span><br><span class="line">    <span class="keyword">final</span> ReentrantLock takeLock = <span class="keyword">this</span>.takeLock;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 实际操作前先锁定，调用lockInterruptibly锁定，且这个方法响应中断</span></span><br><span class="line">    <span class="comment">// 此处需要响应中断，因为这个方法会阻塞线程</span></span><br><span class="line">    takeLock.lockInterruptibly();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 若队列为空，则当前线程需要等待，直到被其他线程唤醒</span></span><br><span class="line">        <span class="keyword">while</span> (count.get() == <span class="number">0</span>) &#123;</span><br><span class="line">            notEmpty.await();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 调用dequeue获取队列的队头元素</span></span><br><span class="line">        x = dequeue();</span><br><span class="line">        <span class="comment">// 获得count的值，然后count + 1</span></span><br><span class="line">        c = count.getAndDecrement();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*************关键点1***************/</span></span><br><span class="line">        <span class="comment">// 若队列中原来的元素数量&gt;1，则表示当前线程拿走一个元素后，队列中还有元素</span></span><br><span class="line">        <span class="comment">// 于是此处唤醒其他消费者线程，让他们获取元素</span></span><br><span class="line">        <span class="comment">// 此处很关键，对应着put方法中的关键点2（注意是put，而不是此方法take），put方法中，</span></span><br><span class="line">        <span class="comment">// 只有添加元素前，队列为空，才会唤醒一个消费者线程，而剩余的消费者线程在此处唤醒</span></span><br><span class="line">        <span class="comment">// 因为这里已经拿到了take锁，不需要为了唤醒消费者线程再次获取take锁</span></span><br><span class="line">        <span class="keyword">if</span> (c &gt; <span class="number">1</span>)</span><br><span class="line">            notEmpty.signal();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        takeLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*******************关键点2*******************/</span></span><br><span class="line">    <span class="comment">// 此处判断，若在获取元素之前，队列是满的，那说明很有可能有生产者线程在等待</span></span><br><span class="line">    <span class="comment">// 因为这里拿走了一个元素，所以队列有空位了，于是就唤醒一个生产者线程，添加元素</span></span><br><span class="line">    <span class="comment">// 值得注意的是，等待的生产者线程可能不止一个，这里只唤醒了一个，剩下的怎么办，</span></span><br><span class="line">    <span class="comment">// 答案就在put方法的关键点2那里，由put方法唤醒了剩下的生产者线程</span></span><br><span class="line">    <span class="keyword">if</span> (c == capacity)</span><br><span class="line">        signalNotFull();</span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 此方法获取队列头节点的值，并将头节点从队列删除 */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> E <span class="title">dequeue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取头节点</span></span><br><span class="line">    Node&lt;E&gt; h = head;</span><br><span class="line">    <span class="comment">// 获取头节点的下一个节点</span></span><br><span class="line">    Node&lt;E&gt; first = h.next;</span><br><span class="line">    <span class="comment">// 让头节点指向自己，也就是让头节点从链表上断开</span></span><br><span class="line">    h.next = h; <span class="comment">// help GC</span></span><br><span class="line">    <span class="comment">// 设置新的头节点，也就是原来头节点的下一个节点</span></span><br><span class="line">    head = first;</span><br><span class="line">    <span class="comment">// 获取原来头节点的值</span></span><br><span class="line">    E x = first.item;</span><br><span class="line">    <span class="comment">// 将原来头节点的值置为空，有助于垃圾回收</span></span><br><span class="line">    first.item = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">// 返回结果</span></span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;以上方法的逻辑也是比较简单的，相信有了注释理解起来不会太难。上面的<code>take</code>方法中，需要中点关注的就是我用注释标记出的<strong>关键点1</strong>和<strong>关键点2</strong>，它们分别对应于<code>put</code>方法中的关键点2和关键点1，这样编写代码的意图就是为了尽量少获取锁，减少频繁获取和释放锁导致的资源消耗，提高性能。除了<code>take</code>方法，还有另外一个元素出队的方法<code>poll</code>，他被重载了两次，下面来看一看：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">poll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取元素数量数量</span></span><br><span class="line">    <span class="keyword">final</span> AtomicInteger count = <span class="keyword">this</span>.count;</span><br><span class="line">    <span class="comment">// 若队列为空，则直接返回null，表示获取失败</span></span><br><span class="line">    <span class="keyword">if</span> (count.get() == <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 以下几句代码于take方法相同</span></span><br><span class="line">    E x = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">int</span> c = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">final</span> ReentrantLock takeLock = <span class="keyword">this</span>.takeLock;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 调用lock()方法加锁，不响应中断，因为当前方法不会阻塞，所以可以不用响应中断</span></span><br><span class="line">    takeLock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 再次判断队列是否为空，因为在上一次判断之后，CPU可能暂停了这个线程，</span></span><br><span class="line">        <span class="comment">// 转而执行其他线程，这个过程中可能有线程向队列中添加了元素</span></span><br><span class="line">        <span class="keyword">if</span> (count.get() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 以下代码均与take方法中相同，不重复解释</span></span><br><span class="line">            x = dequeue();</span><br><span class="line">            c = count.getAndDecrement();</span><br><span class="line">            <span class="keyword">if</span> (c &gt; <span class="number">1</span>)</span><br><span class="line">                notEmpty.signal();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        takeLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (c == capacity)</span><br><span class="line">        signalNotFull();</span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此方法向队列中获取元素，若队列为空线程将会被阻塞，但是需要指定超时时间，</span></span><br><span class="line"><span class="comment"> * 超时后，线程还未获取元素，直接返回；</span></span><br><span class="line"><span class="comment"> * 参数timeout和unit的含义与会超时的offer方法相同，</span></span><br><span class="line"><span class="comment"> * 分别表示超时时间的数量级，已经时间的单位</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">poll</span><span class="params">(<span class="keyword">long</span> timeout, TimeUnit unit)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    E x = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">int</span> c = -<span class="number">1</span>;</span><br><span class="line">    <span class="comment">// 将超时时间转换为纳秒</span></span><br><span class="line">    <span class="keyword">long</span> nanos = unit.toNanos(timeout);</span><br><span class="line">    <span class="comment">// 以下方法与take方法相同，不重复解释</span></span><br><span class="line">    <span class="keyword">final</span> AtomicInteger count = <span class="keyword">this</span>.count;</span><br><span class="line">    <span class="keyword">final</span> ReentrantLock takeLock = <span class="keyword">this</span>.takeLock;</span><br><span class="line">    takeLock.lockInterruptibly();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 若队列为空，则线程需要等待</span></span><br><span class="line">        <span class="keyword">while</span> (count.get() == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 判断等待的剩余时间，若剩余时间&lt;=0，表示已经超时，直接返回null</span></span><br><span class="line">            <span class="keyword">if</span> (nanos &lt;= <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            <span class="comment">// 让当前线程在notEmpty中的等待nanos纳秒，因为awaitNanos方法不精确，</span></span><br><span class="line">            <span class="comment">// 所以这个方法会返回一个值，表示剩余需要等待的时间，所以才有了上一句的if</span></span><br><span class="line">            nanos = notEmpty.awaitNanos(nanos);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 以下代码与take相同，不重复解释</span></span><br><span class="line">        x = dequeue();</span><br><span class="line">        c = count.getAndDecrement();</span><br><span class="line">        <span class="keyword">if</span> (c &gt; <span class="number">1</span>)</span><br><span class="line">            notEmpty.signal();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        takeLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (c == capacity)</span><br><span class="line">        signalNotFull();</span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;好了，关于<code>LinkedBlockingQueue</code>中的方法就说到这里。我们仔细观察这些方法会发现，它们的实现步骤大同小异，我写的很多注释都是重复的，因为每一个方法中都有类似的操作。</p>
<br>

<h2 id="2-6-LinkedBlockingQueue的优势与劣势"><a href="#2-6-LinkedBlockingQueue的优势与劣势" class="headerlink" title="2.6 LinkedBlockingQueue的优势与劣势"></a>2.6 LinkedBlockingQueue的优势与劣势</h2><p>&emsp;&emsp;最后，我们来分析以下<code>LinkedBlockingQueue</code>的优势。这里主要介绍它相对于<code>ArrayBlockingQueue</code>的优势和劣势：</p>
<ul>
<li><code>LinkedBlockingQueue</code>内部使用了两把锁进行线程同步，一把锁同步消费者线程，一把锁同步生产者线程，这也就意味着在添加元素时，不会影响获取元素，反之亦然。由于消费者操作的是队头，而生产者操作的是队尾，所以也不会发生线程安全问题，这样大大提高了队列的吞吐量。但是<code>ArrayBlockingQueue</code>内部只使用一把锁，生产者执行时，消费者也无法执行。</li>
<li><code>LinkedBlockingQueue</code>基于链表实现，所以如果我们要对队列进行随机删除操作，将会非常高效；但是<code>ArrayBlockingQueue</code>基于数组实现，随机删除操作的消耗会很高，以为需要重整元素在数组中的位置。当然，队列是一个尾进头出的容器，所以在使用时还是不要进行随机删除操作。</li>
</ul>
<p>&emsp;&emsp;再说说它的劣势：</p>
<ul>
<li><code>LinkedBlockingQueue</code>中的<code>lock</code>对象使用的是非公平锁，无法根据需求切换为公平锁；而<code>ArrayBlockingQueue</code>可以根据实际情况，选择是否使用公平锁；</li>
</ul>
<br>

<h2 id="2-7-LinkedBlockingQueue的误区"><a href="#2-7-LinkedBlockingQueue的误区" class="headerlink" title="2.7 LinkedBlockingQueue的误区"></a>2.7 LinkedBlockingQueue的误区</h2><p>&emsp;&emsp;这里再提一个很多人对<code>LinkedBlockingQueue</code>的误区。有许多人认为<code>LinkedBlockingQueue</code>既可以是一个有界队列，也可以是一个无界队列，这是一种错误的理解，<strong>LinkedBlockingQueue就是一个有界的阻塞队列</strong>。有人会这样认为的原因是创建<code>LinkedBlockingQueue</code>对象时可以不指定容量，但是不要忘记，如果我们不指定容量，底层实现也会指定一个默认的容量，即<code>int</code>的最大值。在我们向其中添加元素时，底层实现可以确保元素数量不会超过设置好的容量，这就是有界的。</p>
<p>&emsp;&emsp;而什么是无界？举一个最简单的例子，<code>Java</code>中的另一个阻塞队列<code>PriorityBlockingQueue</code>就是无界的，它底层用数组存储元素，我们也可以指定容量，但是当元素个数到达容量时，<code>PriorityBlockingQueue</code>并不会阻塞，而是进行扩容，这就是无界。</p>
<br>

<h1 id="三、总结"><a href="#三、总结" class="headerlink" title="三、总结"></a>三、总结</h1><p>&emsp;&emsp;关于<code>LinkedBlockingQueue</code>就先说这么多吧，重点是要理解各种阻塞队列的结构，以及最关键的<code>take</code>和<code>put</code>方法实现的原理，只要理解了这些，就能有选择性地，更好地使用这些阻塞队列。</p>
<br>

<h1 id="四、参考"><a href="#四、参考" class="headerlink" title="四、参考"></a>四、参考</h1><ul>
<li><a href="https://mp.weixin.qq.com/s/y6PoK3UbVLwdZoauLX8nsQ" target="_blank" rel="noopener">https://mp.weixin.qq.com/s/y6PoK3UbVLwdZoauLX8nsQ</a></li>
</ul>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-04-11T19:36:26.413Z" itemprop="dateUpdated">2020-04-12 03:36:26</time>
</span><br>


        
        世界是个球，前方总有路！
        
    </div>
    
    <footer>
        <a href="http://tewuyiang.gitee.io/blog">
            <img src="/blog/img/avatar.jpg" alt="特务依昂">
            特务依昂
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/Java%E5%AE%B9%E5%99%A8/" rel="tag">Java容器</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/&title=《阻塞队列——LinkedBlockingQueue源码分析》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/&title=《阻塞队列——LinkedBlockingQueue源码分析》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《阻塞队列——LinkedBlockingQueue源码分析》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">并发——深入分析ReentrantLock的实现原理</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94ArrayBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">阻塞队列——ArrayBlockingQueue源码分析</h4>
      </a>
    </div>
  
</nav>



    




















</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/blog/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>特务依昂 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/&title=《阻塞队列——LinkedBlockingQueue源码分析》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/&title=《阻塞队列——LinkedBlockingQueue源码分析》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《阻塞队列——LinkedBlockingQueue源码分析》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '人呢，怎么不见了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!欢迎回来!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
